package com.lewis.anf.servlet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.lewis.anf.ProbeStart;

public class AnfProbe extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String xml = ProbeStart.probe();
		//save it to file
		File file = null;
		  try {
	        	file = new File(getServletContext().getRealPath("/")+ "/anfdata.xml");
	        	FileWriter fwriter = new FileWriter(file);
				fwriter.write(xml);
				fwriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
//		file = new File(getServletContext().getRealPath("/")+ "/anfdata.xml");
		//translate it to html
		  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		  try
		  {
		   DocumentBuilder db=dbf.newDocumentBuilder();
		   Document doc=db.parse(file);
		   DOMSource source=new DOMSource(doc);
		   StreamResult result=new StreamResult(res.getWriter());
		   InputStream is = getClass().getResourceAsStream("../anf.xsl");
		            StreamSource ss=new StreamSource(is);
		            TransformerFactory tff = TransformerFactory.newInstance();
		            Transformer tf = tff.newTransformer(ss);
		            tf.setOutputProperty("encoding", "utf-8");
		            tf.transform(source, result);
		  }
		        catch(ParserConfigurationException e){e.printStackTrace();}
		        catch(SAXException e){e.printStackTrace();}
		        catch(IOException e){e.printStackTrace();}
		        catch(TransformerConfigurationException e){e.printStackTrace();}
		        catch(TransformerException e){e.printStackTrace();}

		
		PrintWriter out = res.getWriter();
		out.flush();
	}
	
	

}
